//
//  MCUpdateGoodsCategoryViewController.swift
//  StoreManage
//
//  Created by MC on 2018/9/12.
//  Copyright © 2018年 MC. All rights reserved.
//

import UIKit


class MCUpdateGoodsCategoryViewController: MCViewController {
    
    public var goodsId = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        
        baseSetting()
        
        initUI()
        
        sendNetworking()
    }
    
    // MARK: - Setter & Getter
    private lazy var colleciontView: MCCollectionView = {
        
        //  68  97
        let layout = UICollectionViewFlowLayout.init()
        layout.scrollDirection = UICollectionViewScrollDirection.vertical
        
        let margin : CGFloat = MCAdaptationModel(26)
        let spacing : CGFloat = MCAdaptationModel(30)
        let itemWidth : CGFloat = (MCScreenWidth - margin * 2 - spacing * 2) / 3
        let itemHeight : CGFloat = MCAdaptationModel(32)
        
        layout.sectionInset = UIEdgeInsetsMake(15, 26, 10, 26)
        
        layout.itemSize = CGSize.init(width: itemWidth, height: itemHeight)
        layout.minimumLineSpacing = 15
        layout.minimumInteritemSpacing = CGFloat(margin)
        
        let collectionView = MCCollectionView.init(frame: CGRect.zero, collectionViewLayout: layout)
        collectionView.backgroundColor = UIColor.white
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.delegate = self
        collectionView.dataSource = self
        
        collectionView.register(MCUpdateGoodsCategoryCell.classForCoder(), forCellWithReuseIdentifier: "cell")
        return collectionView
    }()
    
    lazy var dataArrayM: NSMutableArray = {
        let array = NSMutableArray()
        return array
    }()
}

//MARK: 通知回调，闭包回调，点击事件
extension MCUpdateGoodsCategoryViewController {
    @objc func rightItemClicked() {
        
        let arrayM = NSMutableArray()
        
        for model in dataArrayM {
            let tempModel = model as! MCGoodsCategoryModel
            if tempModel.isContains.intValue == 1 {
                arrayM.add(["selfCategoryId" : tempModel.selfCategoryId.intValue])
            }
        }
        
        let para = [
            "categoryList" : arrayM,
            "goodsId"      : goodsId
            ] as [String : Any]
        
        MCNetwork.POST(JAVA_editGoodsOfSelfCategory, para, success: { (data)
            in
            
            MCHUD_text(message: "更新商品分类成功", view: self.view, delay: 1.0)
            
            
            MCNotification_post(name: NOTIFICATION_updateGoodsCategory, object: nil)
            
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
                self.navigationController?.popViewController(animated: true)
            })
        })
    }
}


//MARK: 网络请求
extension MCUpdateGoodsCategoryViewController {
    
    func sendNetworking() {
        
        let para = [
            "goodsId" : goodsId
        ]
        
        
        MCNetwork.POST(JAVA_querySelfCategoryPage, para, success: { (data) in
            let dataArray = data.arrayObject ?? []
            
            
            if dataArray.count == 0 {
                self.colleciontView.showBgImage()
            } else {
                
                self.colleciontView.hideBgImage()
                
                for dict in dataArray {
                    let model = MCGoodsCategoryModel()
                    model.setValuesForKeys(dict as? [String:Any] ?? [:])
                    self.dataArrayM.add(model)
                }
            }
            

            self.colleciontView.reloadData()
        })
    }
}

//MARK: UI的处理,通知的接收
extension MCUpdateGoodsCategoryViewController {
    
    func baseSetting() {
        self.title = "选择分类"
        
        navigationItem.rightBarButtonItem = MCSetBarButtonItem_text("完成", target: self, selector: #selector(rightItemClicked))
    }
    
    
    func initUI() {
        view.addSubview(colleciontView)
        colleciontView.snp.remakeConstraints { (make) ->Void in
            make.edges.equalTo(view)
        }
    }
}

extension MCUpdateGoodsCategoryViewController : UICollectionViewDelegate,UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataArrayM.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! MCUpdateGoodsCategoryCell
        
        for view in cell.contentView.subviews {
            view.removeFromSuperview()
        }
        
        cell.model = dataArrayM[indexPath.row] as! MCGoodsCategoryModel
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let model = dataArrayM[indexPath.row] as! MCGoodsCategoryModel
        if model.isContains == 0 {
            model.isContains = 1
        } else {
            model.isContains = 0
        }
        colleciontView.reloadData()
    }
}

